package com.hc;

import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBCPUtil {
    private static BasicDataSource dataSource;

    static {
        try {
            dataSource = new BasicDataSource();
            //1.必须的驱动信息
            dataSource.setDriverClassName(PropertiesUtil.getDriverClassName());
            //2.必须的url地址
            dataSource.setUrl(PropertiesUtil.getUrl());
            //3.必须的数据库访问名称
            dataSource.setUsername(PropertiesUtil.getUsername());
            //4.必须的数据库访问密码
            dataSource.setPassword(PropertiesUtil.getPassword());
            //5.非必须信息配置
            dataSource.setInitialSize(Integer.parseInt(PropertiesUtil.getInitialSize()));
            dataSource.setMaxActive(Integer.parseInt(PropertiesUtil.getMaxActive()));
            dataSource.setMaxIdle(Integer.parseInt(PropertiesUtil.getMaxIdle()));
            dataSource.setMinIdle(Integer.parseInt(PropertiesUtil.getMinIdle()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            return null;
        }
    }

    public static void close(Connection connection, ResultSet resultSet, Statement statement){
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
